package com.tieto.user.bean;

import javax.annotation.PostConstruct;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.tieto.user.FacesUtil;
import com.tieto.user.model.Role;
import com.tieto.user.model.User;
import com.tieto.user.service.UserService;

@Component
@Scope("request")
@Slf4j
@SuppressWarnings("PMD.UnusedPrivateField")
public class EditUserBean {
    @Getter
    @Setter
    private String username;
    @Getter
    @Setter
    private User user = new User();
    @Getter
    @Setter
    private String repeatedPassword;
    @Setter
    @Autowired
    UserService userService;
    @SuppressWarnings("pmd.UnusedPrivateField")
    @Getter
    private Role[] roles = Role.values();

    @PostConstruct
    // TODO initialize is called in funny places. What if user remains null?
    public void initialize() {
        username = getRequestParameter("username");
        log.debug("initialize(): username: {}", username);
        if (username != null) {
            user = userService.findOne(username);
        }
    }

    protected String getRequestParameter(String parameterName) {
        return FacesUtil.getRequestParameter(parameterName);
    }

    /**
     * Called from editUser.xhtml page when user presses Update button.
     */
    public String update() {
        log.debug("update(): user: {}", user);
        userService.update(user);
        user = new User();
        return "userSaved";
    }
}
